package org.hughie.sync;

import org.hughie.api.FundApisMapping;
import org.hughie.common.FundSyncType;
import org.hughie.http.IHttpInvoker;
import org.hughie.mapper.BondPositionMapper;
import org.hughie.mapper.StockPositionMapper;
import org.hughie.model.fmn.BondFMN;
import org.hughie.model.fmn.PositionInfoFMN;
import org.hughie.model.fmn.StockFMN;
import org.hughie.model.po.BatchJob;
import org.hughie.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author hughie.cheng
 * @date 2024/3/6
 */
@Component
public class FundPositionInfoTask implements FundSyncTask {

    @Autowired
    private IHttpInvoker invoker;

    @Autowired
    private BondPositionMapper bondMapper;
    @Autowired
    private StockPositionMapper stockMapper;

    @Override
    public String getTaskCode() {
        return FundSyncType.POSITION.getTaskName();
    }

    @Override
    public void sync(String fundCode) {
        PositionInfoFMN positionInfoFMN = invoker.get(FundApisMapping.FUND_POSITION_INFO, fundCode, TimeUtil.getCurrentMills());
        savePosition(fundCode,positionInfoFMN);
    }

    @Transactional
    void savePosition(String fundCode, PositionInfoFMN positionInfoFMN){
        List<StockFMN> stocks = positionInfoFMN.getFundStocks();
        List<BondFMN> bonds = positionInfoFMN.getFundboods();
        stockMapper.save(fundCode,stocks);
        bondMapper.save(fundCode,bonds);
    }

    @Override
    public void syncBatch(List<BatchJob> jobs) {
        jobs.forEach(t -> sync(t.getFundCode()));
    }
}
